package com.example.csh.service;

import com.example.csh.dto.AuthResponse;
import com.example.csh.dto.LoginDto;
import com.example.csh.dto.RegisterDto;
import com.example.csh.entity.User;
import com.example.csh.mapper.UserMapper;
import com.example.csh.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;


import java.util.Date;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    private final AuthenticationManager authenticationManager;
    private final JwtUtils jwtUtils;

    public UserService(AuthenticationManager authenticationManager, JwtUtils jwtUtils) {
        this.authenticationManager = authenticationManager;
        this.jwtUtils = jwtUtils;
    }

    public ResponseEntity<?> login(LoginDto loginDto) {
        User user = userMapper.findByPhone(loginDto.getPhone());
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        user.getUsername(),
                        loginDto.getPassword()));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String jwt = jwtUtils.generateToken((UserDetails) authentication.getPrincipal());
        AuthResponse response = new AuthResponse(jwt);
        return ResponseEntity.ok(response);
    }
    public ResponseEntity<?> register(RegisterDto registerDto) {
        if (userMapper.findByUsername(registerDto.getUsername()) != null) {
            return ResponseEntity.badRequest().body("用户名已被使用");
        }
        if (userMapper.countByPhone(registerDto.getPhone()) > 0) {
            return ResponseEntity.badRequest().body("手机号已被注册");
        }
        // 创建新用户
        User newUser = new User();
        newUser.setUsername(registerDto.getUsername());
        newUser.setPassword(passwordEncoder.encode(registerDto.getPassword())); // 加密密码
        newUser.setPhone(registerDto.getPhone());
        newUser.setAvatar(registerDto.getAvatar());
        newUser.setCreateTime(new Date());
        newUser.setUpdateTime(new Date());

        // 保存用户
        userMapper.insertUser(newUser);

        return ResponseEntity.ok("用户注册成功");
    }
}
